/*
 * Copyright (C) 2012 Rothens
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package rpg;

import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

/**
 * rothens.tarhely.biz
 * @author Rothens
 */
public class KeyboardListener implements KeyListener {
	
	private boolean[] key_up = new boolean[256];
	private boolean[] key_down = new boolean[256];
	
	private String cache = "";
	
	//this is a singleton! We only want ONE instance all the time!
	private static KeyboardListener instance = new KeyboardListener();
	
	protected KeyboardListener(){
		
	}
	
	/**
	 * Checks if a key is pressed
	 * @param key the key to check
	 * @return true, if the key is pressed down in that frame
	 */
	public boolean isKeyDown(int key){
		return key_down[key];
	}
	
	/**
	 * 
	 * @param key the key to check
	 * @return true, if that key was released in that frame
	 */
	public boolean isKeyUp(int key){
		return key_up[key];
	}
	
	/**
	 * Gets the key cache
	 * @return the key cache
	 */
	public String getCache(){
		return cache;
	}
	
	public void tick(){
		key_up = new boolean[256]; //we don't want to store released keys for more than a frame!
		if(cache.length() > 1024)
			cache = "";
	}
	
	public static KeyboardListener getInstance(){
		return instance;
	}

	
	@Override
	public void keyPressed(KeyEvent e) {
		int key = e.getKeyCode();
		if(key >= 0 && key < 256){
			key_down[key] = true;
			key_up[key] = false;
		}
	}

	@Override
	public void keyReleased(KeyEvent e) {
		int key = e.getKeyCode();
		if(key >= 0 && key < 256){
			key_down[key] = false;
			key_up[key] = true;
		}
	}
	
	@Override
	public void keyTyped(KeyEvent e) {
		cache += e.getKeyChar();
	}
	
}
